import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { listRecordApi, exportExcelApi } from '../api/record'
import { usePipeline } from './usePipeline'
const { searchPipelineId } = usePipeline()
const recordListLoading = ref(true)
const recordList = reactive({
  arr: []
})
const rangeRecordTime = ref()
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)
const exportExcelLoading = ref(false)

async function getRecordList() {
  recordListLoading.value = true
  const { data: res } = await listRecordApi(
    {
      pipelineId: searchPipelineId.value,
      startRecordTime: rangeRecordTime.value ? rangeRecordTime.value[0] : '',
      endRecordTime: rangeRecordTime.value ? rangeRecordTime.value[1] : ''
    },
    currentPage.value,
    pageSize.value
  )
  recordList.arr = res.data.records
  total.value = res.data.total
  setTimeout(() => {
    recordListLoading.value = false
  }, 500)
}

async function exportExcel() {
  exportExcelLoading.value = true
  const res = await exportExcelApi({
    pipelineId: searchPipelineId.value,
    startRecordTime: rangeRecordTime.value ? rangeRecordTime.value[0] : '',
    endRecordTime: rangeRecordTime.value ? rangeRecordTime.value[1] : ''
  })
  // 文件下载失败
  if (res.data.type === 'application/json') {
    const reader = new FileReader()
    reader.readAsText(res.data, 'utf-8')
    reader.onload = () => {
      const { msg } = JSON.parse(reader.result)
      ElMessage.error({
        message: msg,
        dangerouslyUseHTMLString: true
      })
      exportExcelLoading.value = false
    }
    return
  }
  const link = document.createElement('a')
  const url = window.URL || window.webkitURL || window.moxURL
  const blob = new Blob([res.data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  link.href = url.createObjectURL(blob)
  link.download = decodeURIComponent(res.headers.get('content-disposition').split('filename=')[1])
  link.click()
  url.revokeObjectURL(link.href)
  exportExcelLoading.value = false
  ElMessage.success('历史数据导出成功')
}

export const useRecord = () => {
  return {
    recordListLoading,
    recordList,
    rangeRecordTime,
    currentPage,
    pageSize,
    total,
    exportExcelLoading,
    getRecordList,
    exportExcel
  }
}
